(function ($) {
    //默认参数
    var defaluts = {
        searchName: '.ySearchSelect'
    };

    $.fn.extend({
        "ySearchSelect": function (options) {
            defaluts.searchName = options;
            var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数
            return this.each(function () {  //这里的this 就是 jQuery对象。这里return 为了支持链式调用
                init(opts);
            });

        }
    });
    //初始化插件
    let productInfo = [];
    function init(o){
        $(document).click(function(){
            $(".ySearchSelect table").hide();
            $(".ySearchSelect .input-text").hide();
            $(".ySearchSelect .layui-form.layui-border-box.layui-table-view").hide();
            $(".ySearchSelect i.layui-edge").removeClass("select");
        });

        $(o.searchName+" .layui-input").click(function(event){
            //阻止document点击事件
            event.stopPropagation();
            if($(this).siblings(".input-text").length <= 0){
                var str = '<div class="input-text">'+
                    '<input type="text" name="" placeholder="输入关键字" class="layui-input">'+
                    '</div>';
                $(o.searchName).append(str);
            }
            if($(this).siblings("table").css("display") == "none"){
                let ids = $(o.searchName).attr("data-id");
                table.render({
                    elem: '#productcodeselect_'+ids,
                    id: 'productcodeselecttableid_'+ids,
                    data: productInfo,
                    url:'initStock/add/getProductInfo',
                    cols: [[
                        {field: 'productCode', width: 220, title: '产品编码'},
                        {field: 'specificationCode', width: 120, title: '规格编码'},
                        {field: 'productCname', width: 120, title: '中文名称'},
                        {field: 'productEname', width: 120, title: '英文名称'},
                        {field: 'directoryName', width: 120, title: '产品目录'}
                    ]],
                    height: 200
                });
                table.on('row(productcodeselecttable_'+ids+')', function(obj){
                    let data = obj.data;
                    let tableData = table.cache["storageproductstableid"];
                    $.each(tableData,function(index,value){
                        if(value.tempId == ids){
                            data.tempId = ids;
                            //金额小计（默认为零）
                            data["moneySubtotal"] = "0";
                            //数量（默认为零）
                            data["productNum"] = "0";
                            //托数
                            data["totalTray"] = "0";
                            //每托量
                            data["trayNumber"] = "0";
                            //件数
                            data["boxAmount"] = "0";
                            //每件数量
                            data["everyBoxAmount"] = "0";
                            //毛重小计
                            data["grossWeightSubtotal"] = "0";
                            //净重小计
                            data["netWeightSubtotal"] = "0";
                            //体积小计
                            data["bulkSubtotal"] = "0";
                            //外包装尺寸
                            data["outerPackingSize"] = getBulkSubtotal(data);

                            //配件相关信息
                            //产品编码
                            let productCode = data.productCode;
                            //规格编码
                            let specNo = data["specificationCode"];
                            let tempPartsList = [];
                            if(!isEmpty(specNo)){
                                data["specNo"] = specNo;
                                data["productSpecExplanation"] = data["specificationExplanation"];
                                data["fcUnitPrice"] = data["unitPrice"];
                                $.ajax({
                                    url: "offer/getProductPartsInfoBySpecNo?specNo=" + specNo + "&productCode=" + productCode,
                                    async:false,
                                    success:function(res){
                                        if(res.status == 200){
                                            for(let i in res.data){
                                                let partTempId = GenNonDuplicateID(3) + (index+1);
                                                res.data[i]["tempId"] = partTempId;
                                                res.data[i]["parentTempId"] = data.tempId;
                                                //成品比例(默认1)
                                                res.data[i]["proportionFinishedProducts"] = 1;
                                                //配件比例(默认1)
                                                res.data[i]["partsFinishedProducts"] = 1;
                                                tempPartsList.push(res.data[i]);
                                            }
                                        }else {
                                            layer.msg("获取信息失败，请稍后再试！", {icon: 5});
                                        }
                                    }
                                });
                            }
                            data["partsList"] = tempPartsList;
                            tableData[index] = data;
                        }
                    });
                    table.reload('storageproductstableid',{data:tableData});
                });
                $(this).siblings("i").addClass("select");
                $(this).siblings("table").show();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").show();
                $(this).siblings(".input-text").show();
            }else{
                $(this).siblings("i").removeClass("select");
                $(this).siblings("table").hide();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").hide();
                $(this).siblings(".input-text").hide();
            }
            $(o.searchName+" .input-text input").focus();
            $(o.searchName+" .input-text").width(605);

            //键盘监听事件
            $(o.searchName+" .input-text input").keyup(function(event){
                if(event.keyCode != 38 && event.keyCode != 40 && event.keyCode == 13){
                    ySearchSelectMate($(this).val(),o.searchName);
                }
            });
        });
    }

    //获取外包装尺寸:外包装尺寸=外包装长*外包装宽*外包装高
    function getBulkSubtotal(data) {
        //外包装长
        let outerPackingLong = data["outerPackingLong"];
        //外包装宽
        let outerPackingWide = data["outerPackingWide"];
        //外包装高
        let outerPackingHeight = data["outerPackingHeight"];
        if(!isEmpty(outerPackingLong) && !isEmpty(outerPackingWide) && !isEmpty(outerPackingHeight)){
            return outerPackingLong + "*" + outerPackingWide + "*" + outerPackingHeight;
        }
        return "";
    }

    //匹配搜索，不匹配则隐藏。
    function ySearchSelectMate(value,name){
        value = $.trim(value.toString()); // 去掉两头空格
        let ids = $(name).attr("data-id");
        let tableData = table.cache["storageproductstableid"];
        $.each(tableData, function(index, values){
            if(values.tempId == ids){
                tableData[index]["productCode"] = value;
                //$(".value_"+values.tempId).html(value);
            }
        });
        //模糊查询表格并刷新
        table.reload('productcodeselecttableid_'+ids,{where: {
                info:value
            }});
    }
})(window.jQuery);

var form = layui.form, laydate = layui.laydate, partsParentTempId = "", annexList = [], customsCode =[], upload = layui.upload, table = layui.table, $ = layui.jquery, id = getQueryVariable("id");

layui.use(['tableEdit',"selectInput"], function () {
    let layer = layui.layer,
        selectInput = layui.selectInput;

    lay('.starttime').each(function () {
        laydate.render({
            elem: this,
            type: 'date',
            // showBottom: false,
            done: function (value, date, endDate) {
                if (this.elem[0].id == "actualdischargedateatd" || this.elem[0].id == "wldate") {
                    if (value != "") {
                        $("." + this.elem[0].id + "text").css("background", "#fff");
                    } else {
                        $("." + this.elem[0].id + "text").css("background", "red");
                    }
                }

            }
        });
    });


    //客户信息
    let customerInfo = [];
    //收款银行信息
    let bankAccountList = [];
    //币种
    let currencyInfo = [];
    //美元编码
    let usdCode = "";
    //美元
    let usdName = "";
    //美金汇率
    let usdRate = "";
    //美金对人名币汇率
    let rmbRate = "";
    //起运地、目的地信息
    let transitPlace = [];
    //收款类型
    let paymentTypeList = [];
    //价格术语
    let priceTerms = [];
    //业务模式
    let businessModel = [];
    //公司信息
    let companyInfo = [];
    //仓库信息
    let warehouseList = [];
    //费用类型
    let costType = [];
    //单位
    let unitOfQuantity = [];
    //验货进度
    let inspectionProgress = [];
    //国家信息
    let country = [];
    //业务员
    let salesmanInfo = [];
    //运输方式
    let modeOfTransport = [];
    //货柜型号
    let containerModel = [];
    //删除的老的附件ID集合
    let deleteAnnexIds = [];
    //采购标签 判断是否有此角色
    let purchaseLabel = getAllRolesByCurr("ExportBusiness_Shipmentdetails_Purchase");
    //外销标签 判断是否有此角色
    let exportConcatLabel = getAllRolesByCurr("ExportBusiness_Shipmentdetails_ExportConcat");

    layer.ready(function () {

        setCustomerInfo("");

        //发票总额 无权限需隐藏
        if(purchaseLabel){
            $(".Authority-Label").hide();
        }
        $.ajax({
            url: "otherOutStock/getAllUserInfo",
            success: function (data) {
                if (data.status == 200) {
                    salesmanInfo = data.data;
                    for (let i in salesmanInfo) {
                        $("#salesmanCode").append(new Option(salesmanInfo[i].name, salesmanInfo[i].code));
                    }
                }
            }
        });

        //获取运输方式
        $.ajax({
            url:"offer/getModeOfTransport",
            success:function(data){
                if(data.status == 200){
                    modeOfTransport = data.data;
                    for(let i in data.data){
                        $('#transportCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取所有公司信息
        $.ajax({
            url: "receivePayment/getCompanyInfo",
            success: function (data) {
                if (data.status == 200) {
                    companyInfo = data.data;
                    let initCode = "";
                    let initName = "";
                    for (let i in data.data) {
                        if (data.data[i].isProxy == 1) {
                            initCode = data.data[i].code;
                            initName = data.data[i].name;
                        }
                        //公司名称
                        $('#signingCompanyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    if (!isEmpty(initCode)) {
                        $('#signingCompanyCode').val(initCode);
                        $('#signingCompanyName').val(initName);
                        getBankInfo(initCode);
                    }
                    form.render('select');
                }
            }
        });

        //获取起运地
        $.ajax({
            url: "offer/getTransitPlace",
            success: function (data) {
                if (data.status == 200) {
                    transitPlace = data.data;
                    for (let i in data.data) {
                        $('#transitPlaceCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取目的地/国家信息
        $.ajax({
            url:"offer/getCountry",
            success:function(data){
                if(data.status == 200){
                    country = data.data;
                    for (let i in data.data) {
                        $('#destinationCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取币种
        $.ajax({
            url: "receivePayment/getCurrencyInfo",
            success: function (data) {
                if (data.status == 200) {
                    currencyInfo = data.data;
                    for(let i in data.data){
                        if(data.data[i].englishName == "USD"){
                            //美元编码
                            usdCode = data.data[i].code;
                            //美元名称
                            usdName = data.data[i].name;
                            //获取美金兑人名币汇率
                            rmbRate = data.data[i].exchangeRate;

                            $("#rmbRate").val(rmbRate);
                        }else if(data.data[i].englishName == "RMB"){
                            //人名币兑美元汇率
                            usdRate = data.data[i].exchangeRate;
                        }
                        $('#currencyCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    if(usdCode.length > 0){
                        //默认USD选中
                        $('#currencyCode').val(usdCode);
                        $('#currency').val(usdName);
                        //美元汇率为1
                        $('#usdRate').val(1);
                    }
                    form.render('select');
                }
            }
        });

        //获取价格术语信息
        $.ajax({
            url: "offer/getPriceTerms",
            success: function (data) {
                if (data.status == 200) {
                    priceTerms = data.data;
                    for (let i in data.data) {
                        $('#priceTermsCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取业务模式信息
        $.ajax({
            url: "offer/getBusinessModel",
            success: function (data) {
                if (data.status == 200) {
                    businessModel = data.data;
                    for (let i in data.data) {
                        $('#businessModelCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });


        //获取收款类型
        $.ajax({
            url: "receivePayment/getReceivePaymentTypeInfo",
            success: function (data) {
                if (data.status == 200) {
                    paymentTypeList = data.data;
                    for (let i in paymentTypeList) {
                        $('#paymentMethodCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取数量单位
        $.ajax({
            url:"resourceSamples/getUnitOfQuantityInfo",
            success:function(data){
                if(data.status == 200){
                    unitOfQuantity = data.data;
                }
            }
        });

        $("#operator").val(user.name);


        //获取仓库信息
        $.ajax({
            url: "transfer/getWarehouse",
            success: function (data) {
                if (data.status == 200) {
                    warehouseList = data.data;
                    for (let i in data.data) {
                        $("#warehouseCode").append("<option value=\"" + data.data[i].code + "\">" + data.data[i].name + "</option>");
                    }
                    form.render('select');
                }
            }
        });

        //获取费用类型
        $.ajax({
            url:"offer/getCostType",
            success:function(data){
                if(data.status == 200){
                    costType = data.data;
                }
            }
        });

        //获取验货进度
        $.ajax({
            url:"offer/getInspectionProgress",
            success:function(data){
                if(data.status == 200){
                    inspectionProgress = data.data;
                }
            }
        });

        //获取货柜型号
        $.ajax({
            url:"offer/getContainerModel",
            async:false,
            success:function(data){
                if(data.status == 200){
                    containerModel = data.data;
                    for(let i in data.data){
                        $('#containerTypeCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

    });

    //监听货柜型号下拉框
    form.on("select(containerTypeCode)", function(data){
        if(data.value === ""){
            $('#containerType').val("");
            return;
        }
        for(let i in containerModel){
            if(data.value == containerModel[i].code){
                $('#containerType').val(containerModel[i].name);
            }
        }
    });

    function setCustomerInfo(initData) {
        //客户名称
        let ins = selectInput.render({
            elem: '#customerSelect',
            name: 'customerSelect',
            initValue: initData,
            hasSelectIcon: true,
            placeholder: '请输入名称',
            data: [],
        })
        //监听输入
        ins.on('itemInput(customerSelect)', function (obj) {
            let tempData = [];
            $.ajax({
                url: "basicInformation/getCustomerInfo?info=" + obj.value,
                async: false,
                success: function (res) {
                    if (res.status == 200) {
                        customerInfo = res.data.customerInfo;
                        for (let i in customerInfo) {
                            customerInfo[i]["value"] = customerInfo[i].code;
                            tempData.push(customerInfo[i]);
                        }
                    }
                }
            })
            ins.addSelect(tempData)
        })

        // 监听select 选择事件
        ins.on('itemSelect(customerSelect)', function (obj) {
            let code = obj.data;
            let name = obj.textContent;
            $("#customerCode").val(code);
            $("#customerName").val(name);
            //获取客户等级
            $("#customerLevelName").val("");
            $("#customerLevelCode").val("");
            for(let i in customerInfo){
                if(customerInfo[i].code == code){
                    let customerLevelName = customerInfo[i]["customerLevelName"];
                    let customerLevelCode = customerInfo[i]["customerLevelCode"];
                    if(!isEmpty(customerLevelName)){
                        $("#customerLevelName").val(customerLevelName);
                        $("#customerLevelCode").val(customerLevelCode);
                        break;
                    }
                }
            }
        });
    }

    //监听业务员下拉框
    form.on("select(salesmanCode)", function(data){
        if(data.value === ""){
            return;
        }
        for(let i in salesmanInfo){
            if(data.value == salesmanInfo[i].code){
                $('#salesmanName').val(salesmanInfo[i].name);
                break;
            }
        }
    });


    //监听币种下拉框
    form.on('select(currencyCode)', function (data) {
        if(data.value === ""){
            return;
        }
        let englishName = getCurrencyInfoByCode(data.value, 1);
        if(englishName == "RMB"){
            //如果选择rmb，则对应rmb汇率为1
            $("#rmbRate").val(1);
            $("#usdRate").val(usdRate);
        }else if(englishName == "USD"){
            //如果选择美元，则对应美金汇率为1
            $("#rmbRate").val(rmbRate);
            $("#usdRate").val(1);
        }else{
            //其它
            let exchangeRate = getCurrencyInfoByCode(data.value, 3);
            $("#usdRate").val(exchangeRate);
            $("#rmbRate").val(rmbRate);
        }
        let name = getCurrencyInfoByCode(data.value, 2);
        $("#currency").val(name);
    })

    //获取币种信息：code:编码  type(1:获取英文名称 2:获取name 3:获取汇率)
    function getCurrencyInfoByCode(code, type) {
        for (let i in currencyInfo) {
            if (currencyInfo[i].code == code) {
                let res = "";
                switch (type) {
                    case 1:
                        res = currencyInfo[i].englishName;
                        break;
                    case 2:
                        res = currencyInfo[i].name;
                        break;
                    case 3:
                        res = currencyInfo[i].exchangeRate;
                        break;
                }
                return res;
            }
        }
        return "";
    }


    //监听启运地下拉框
    form.on("select(transitPlaceCode)", function (data) {
        if (data.value === "") {
            return;
        }
        let name = getDestinationName(data.value);
        $("#transitPlaceName").val(name);
    });

    //监听目的地下拉框
    form.on("select(destinationCode)", function (data) {
        if(data.value === ""){
            return;
        }
        let name = getCountryNameByCode(data.value);
        $("#destinationName").val(name);
    });

    function getCountryNameByCode(code) {
        let name = "";
        for(let i in country){
            if(country[i].code == code){
                name = country[i].name;
                break;
            }
        }
        return name;
    }

    function getDestinationName(code) {
        for (let i in transitPlace) {
            if (transitPlace[i].code == code) {
                return transitPlace[i].name;
            }
        }
        return "";
    }

    //监听收款类型下拉框
    form.on("select(paymentMethodCode)", function (data) {
        if (data.value === "") {
            return;
        }
        let name = getNameByCode(data.value, paymentTypeList);
        $("#paymentMethodName").val(name);
    });

    //监听价格术语下拉框
    form.on("select(priceTermsCode)", function (data) {
        if (data.value === "") {
            return;
        }
        let name = getNameByCode(data.value, priceTerms);
        $('#priceTermsName').val(name);
    });

    //监听业务模式下拉框
    form.on("select(businessModelCode)", function (data) {
        if (data.value === "") {
            return;
        }
        let name = getNameByCode(data.value, businessModel);
        $('#businessModelName').val(name);
    });

    //监听签约公司下拉框
    form.on("select(signingCompanyCode)", function (data) {
        if (data.value === "") {
            return;
        }
        let name = getNameByCode(data.value, companyInfo);
        $('#signingCompanyName').val(name);
        //重新查询银行信息
        getBankInfo(data.value);
    });

    //监听收款银行名称下拉框
    form.on("select(bankCode)", function (data) {
        if (data.value === "") {
            return;
        }
        let name = getNameByCode(data.value, bankAccountList);
        $('#bankName').val(name);
    });

    function getNameByCode(code, list) {
        for (let i in list) {
            if (list[i].code == code) {
                return list[i].name;
            }
        }
        return "";
    }

    function getBankInfo(code) {
        //获取银行账号
        let defaultCode = "";
        let defaultName = "";
        $.ajax({
            url:"receivePayment/getBankAccountInfo?code=" + code,
            async:false,
            success:function(res){
                if(res.status == 200){
                    //银行信息
                    bankAccountList = res.data.bankAccountList;
                    $('#bankCode').empty();
                    for(let i in bankAccountList){
                        if(defaultCode.length == 0 && bankAccountList[i].defaultBusinessUse == 1){
                            defaultCode = bankAccountList[i].code;
                            defaultName = bankAccountList[i].name;
                        }
                        $('#bankCode').append(new Option(bankAccountList[i].name + "_" + bankAccountList[i].bankAccount, bankAccountList[i].code));
                    }
                    if(defaultCode.length > 0){
                        $('#bankCode').val(defaultCode);
                        $("#bankName").val(defaultName);
                    }else{
                        $('#bankCode').val(bankAccountList[0].code);
                        $("#bankName").val(bankAccountList[0].name);
                    }

                    form.render('select');
                }
            }
        });
    }

    //监听仓库下拉框
    form.on('select(warehouseCode)', function (data) {
        if (data.value === "") {
            return;
        }
        let name = getWarehouseName(data.value);
        $("#warehouseName").val(name);
    })

    function getWarehouseName(code) {
        for (let i in warehouseList) {
            if (warehouseList[i].code == code) {
                return warehouseList[i].name;
            }
        }
        return "";
    }

    //监听提交
    form.on('submit(form-element)', function (data) {
        //防止重复提交问题
        preventDuplicateSubmissions();
        let indexsl = 0;
        //产品明细数据
        let storageproductsdata = table.cache["storageproductstableid"];
        //费用数据
        let costtabledata = table.cache["costtableid"];
        $.each(storageproductsdata, function (index, value) {
            if (typeof (storageproductsdata[index]["productCode"]) == "undefined" || storageproductsdata[index]["productCode"] == "") {
                layer.msg("产品表第" + (index + 1) + "条产品编码不能为空");
                indexsl++;
                return false;
            } else if (typeof (storageproductsdata[index]["productNum"]) == "undefined" || storageproductsdata[index]["productNum"] == "") {
                layer.msg("产品表第" + (index + 1) + "条数量不能为空");
                indexsl++;
                return false;
            } else if (typeof (storageproductsdata[index]["productUnitName"]) == "undefined" || storageproductsdata[index]["productUnitName"] == "" || storageproductsdata[index]["productUnitName"] == null) {
                storageproductsdata[index]["productUnitName"] = getProductUnitCode(storageproductsdata[index]["productUnitCode"]);
            }

            //配件数据
            let productsatabledata = storageproductsdata[index].partsList;
            if (indexsl == 0 && typeof (productsatabledata) != "undefined") {
                $.each(productsatabledata, function (index, value) {
                    if (typeof (productsatabledata[index]["partsCode"]) == "undefined" || productsatabledata[index]["partsCode"] == "") {
                        layer.msg("产品规格配件表第" + (index + 1) + "条配件编码不能为空");
                        indexsl++;
                        return false;
                    } else if (typeof (productsatabledata[index]["proportionFinishedProducts"]) == "undefined" || productsatabledata[index]["proportionFinishedProducts"] == "") {
                        layer.msg("产品规格配件表第" + (index + 1) + "条成品比例不能为空");
                        indexsl++;
                        return false;
                    } else if (typeof (productsatabledata[index]["partsFinishedProducts"]) == "undefined" || productsatabledata[index]["partsFinishedProducts"] == "") {
                        layer.msg("产品规格配件表第" + (index + 1) + "条配件比例不能为空");
                        indexsl++;
                        return false;
                    }
                });
            }
            if(indexsl > 0){
                return false;
            }
        });

        if (indexsl == 0) {
            $.each(costtabledata, function (index, value) {
                if (typeof (costtabledata[index]["typeCode"]) == "undefined" || costtabledata[index]["typeCode"] == "") {
                    layer.msg("费用表第" + (index + 1) + "条费用类型不能为空");
                    indexsl++;
                    return false;
                } else if (typeof (costtabledata[index]["amount"]) == "undefined" || costtabledata[index]["amount"] == "") {
                    layer.msg("费用表第" + (index + 1) + "条金额不能为空");
                    indexsl++;
                    return false;
                } else if (isEmpty(costtabledata[index]["contractNo"])) {
                    layer.msg("费用表第" + (index + 1) + "条外销合同号不能为空");
                    indexsl++;
                    return false;
                }
            });
        }

        //向后台组装数据
        //获取头部表单数据
        let req = data.field;
        if (indexsl == 0) {
            req["detailList"] = storageproductsdata;

            req["costList"] = costtabledata;
            //获取附件数据
            let annexReqs = table.cache["attachmenttableid"];
            req["annexList"] = annexReqs;
            req["deleteAnnexIds"] = deleteAnnexIds;
            let datas = JSON.stringify(req);

            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:datas,
                url:"carryDetail/add",
                success:function(res){
                    if(res.status == 200){
                        layer.msg("保存成功", {icon: 6});
                        setTimeout(function () {
                            //保存成功则刷新提交过来的界面 并关闭此页面
                            parent.detab("views/jsp/ExportBusiness/shipmentdetails.jsp");
                            parent.intab("views/jsp/ExportBusiness/shipmentdetails.jsp", "出运明细")
                            parent.detab("views/jsp/ExportBusiness/tpl/newupshipmentdetails.jsp" + (id == '' ? '' : '?id=' + id));
                        }, );
                    }else {
                        layer.msg(res.msg, {icon: 5});
                    }
                    return false;
                }
            });

        }
        return false;
    });

    //--产品信息
    let initData = [];
    table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid',
        data: initData,
        toolbar: '#storageproductstoolbar',
        totalRow: true,
        cols: [[
            {checkbox: true, fixed: true},
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'},
            {field: 'saleContractNo', width: 120, title: '外销合同号', edit: 'text'},
            {field: 'productCode', width: 220, title: '产品编码', templet: '#productcodeselect'},
            {field: 'specNo', width: 120, title: '规格编码', edit: 'text'},
            {field: 'lotNo', width: 120, title: '批次', edit: 'text'},
            {field: 'productNum', width: 120, title: '数量', edit: 'text', totalRow: true},
            {field: 'fcUnitPrice', width: 80, title: '单价'},
            {field: 'moneySubtotal', width: 120, title: '金额小计', totalRow: true},
            {field: 'warehouseReceiptNumber', width: 120, title: '入库单号', edit: 'text'},
            {field: 'purchaseNo', width: 120, title: '采购单号', edit: 'text'},
            {field: 'productSpecExplanation', width: 120, title: '规格说明', edit: 'text'},
            {field: 'clientProductNo', width: 120, title: '客户货号', edit: 'text'},
            {field: 'productCname', width: 120, title: '中文名称', edit: 'text'},
            {field: 'productEname', width: 120, title: '英文名称', edit: 'text'},
            {field: 'productCdesc', width: 120, title: '中文描述', edit: 'text'},
            {field: 'productEdesc', width: 120, title: '英文描述', edit: 'text'},
            {field: 'productUnitCode', width: 120, title: '单位', templet: '#unitselect'},
            {field: 'customerInvoiceGoodsName', width: 120, title: '客户开票货物名称', edit: 'text'},
            {field: 'customerInvoiceSpecModel', width: 120, title: '客户开票规格型号', edit: 'text'},
            {field: 'customerMaterialsCode', width: 120, title: '客户物料编码', edit: 'text'},
            {field: 'color', width: 120, title: '颜色', edit: 'text'},
            {field: 'grossWeight', width: 120, title: '毛重', edit: 'text'},
            {field: 'grossWeightSubtotal', width: 120, title: '毛重小计', edit: 'text'},
            {field: 'netWeight', width: 120, title: '净重', edit: 'text'},
            {field: 'netWeightSubtotal', width: 120, title: '净重小计', edit: 'text'},
            {field: 'bulk', width: 120, title: '体积', edit: 'text'},
            {field: 'bulkSubtotal', width: 120, title: '体积小计', edit: 'text'},
            {field: 'totalTray', width: 120, title: '托数', edit: 'text'},
            {field: 'trayNumber', width: 120, title: '每托量', edit: 'text'},
            {field: 'boxAmount', width: 120, title: '件数', edit: 'text'},
            {field: 'everyBoxAmount', width: 120, title: '每件数量', edit: 'text'},
            {field: 'paymentPeriod', width: 120, title: '付款账期', edit: 'text'},
            {field: 'costUnitPrice', width: 120, title: '成本单价'},
            {field: 'costSubtotal', width: 120, title: '成本小计'},
            {field: 'finishedProductCost', width: 120, title: '成品成本'},
            {field: 'accessoriesCost', width: 120, title: '配件成本'},
            {field: 'supplierName', width: 120, title: '供应商'},
            {field: 'clientContractNo', width: 120, title: '客户合同号', edit: 'text'},
            {field: 'outerPackingLong', title: '外包装长', width: 120, edit: 'text'},
            {field: 'outerPackingWide', title: '外包装宽', width: 120, edit: 'text'},
            {field: 'outerPackingHeight', title: '外包装高', width: 120, edit: 'text'},
            {field: 'outerPackingSize', title: '外包装尺寸', width: 120, edit: 'text'},
            {field: 'outerPackingUnit', title: '外包装单位', width: 120, edit: 'text'},
            {fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#storageproductseditor'}]],
        page: false,
        limit: Number.MAX_VALUE,
        height: 380
        , done: function (res, curr, count) {
            if(purchaseLabel){
                //采购标签:控制主表"发票总额",子表"单价"、"金额小计"
                //单价
                $("[data-field='fcUnitPrice']").css("display", "none");
                //金额小计
                $("[data-field='moneySubtotal']").css("display", "none");

            }
            if(exportConcatLabel){
                //外销标签:控制子表"成本单价"、"成本小计"、"成品成本"、"配件成本"、"供应商" 配件表 "成本单价"、"成本小计"、"供应商"
                //成本单价
                $("[data-field='costUnitPrice']").css("display", "none");
                //成本小计
                $("[data-field='costSubtotal']").css("display", "none");
                //成品成本
                $("[data-field='finishedProductCost']").css("display", "none");
                //配件成本
                $("[data-field='accessoriesCost']").css("display", "none");
                //供应商
                $("[data-field='supplierName']").css("display", "none");

            }
            $(".layui-table select").parent(".layui-table-cell").css('overflow', 'visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow', 'visible')
            for(let i in unitOfQuantity){
                $(".productUnitCode").append("<option value=\"" + unitOfQuantity[i].code + "\">" + unitOfQuantity[i].name + "</option>");
            }
            //sum(金额小计)
            let sumMoneySubtotal = 0;
            let patentTableFlag = true;
            for (var i = 0; i < res.data.length; i++) {
                let tempId = res.data[i].tempId;
                let classs = ".y_" + tempId;
                $(classs).ySearchSelect(classs);
                if(!isEmpty(res.data[i]["carryPlanInfo"]) && patentTableFlag){
                    //设置主表部分信息
                    let planInfo = res.data[i].carryPlanInfo;

                    setCustomerInfo(planInfo.customerName);

                    //客户编码
                    $("#customerCode").val(planInfo.customerCode);
                    //客户名称
                    $("#customerName").val(planInfo.customerName);

                    //客户等级
                    $("#customerLevelName").val(planInfo.customerLevelName);
                    $("#customerLevelCode").val(planInfo.customerLevelCode);

                    if(!isEmpty(planInfo.time)){
                        //出运日期
                        $("#time").val(planInfo.time);
                    }

                    if(!isEmpty(planInfo.currencyCode)){
                        //币种
                        $("#currencyCode").val(planInfo.currencyCode);
                        let name = getCurrencyInfoByCode(planInfo.currencyCode, 2);
                        $("#currency").val(name);
                        //人民币汇率
                        $('#rmbRate').val(planInfo.rmbRate);
                        //美元汇率为
                        $('#usdRate').val(planInfo.usdRate);
                    }

                    if(!isEmpty(planInfo.transitPlaceCode)){
                        //启运地
                        let transitPlaceName = getDestinationName(planInfo.transitPlaceCode);
                        $("#transitPlaceCode").val(planInfo.transitPlaceCode);
                        $("#transitPlaceName").val(transitPlaceName);
                    }

                    if(!isEmpty(planInfo.destinationCode)){
                        //目的地
                        let countryName = getCountryNameByCode(planInfo.destinationCode);
                        $("#destinationCode").val(planInfo.destinationCode);
                        $("#destinationName").val(countryName);
                    }

                    if(!isEmpty(planInfo.modeOfTransport)){
                        //运输方式
                        $("#modeOfTransport").val(planInfo.modeOfTransport);
                        /*for(let i in modeOfTransport){
                            if(modeOfTransport[i].code == planInfo.modeOfTransport){
                                let name = modeOfTransport[i].name;
                                $("#modeOfTransport").val(name);
                            }
                        }*/
                    }

                    if(!isEmpty(planInfo.paymentMethodCode)){
                        //收款类型
                        $("#paymentMethodCode").val(planInfo.paymentMethodCode);
                        $("#paymentMethodName").val(planInfo.paymentMethodName);
                    }

                    if(!isEmpty(planInfo.priceTermsCode)){
                        //价格术语
                        let name = getNameByCode(planInfo.priceTermsCode, priceTerms);
                        $("#priceTermsCode").val(planInfo.priceTermsCode);
                        $('#priceTermsName').val(name);
                    }

                    if(!isEmpty(planInfo.salesContractNo)){
                        //销售合同号
                        $('#salesContractNo').val(planInfo.salesContractNo);
                    }

                    if(!isEmpty(planInfo.customerContractNo)){
                        //客户合同号
                        $('#customerContractNo').val(planInfo.customerContractNo);
                    }

                    if(!isEmpty(planInfo.businessModelCode)){
                        //业务模式
                        let name = getNameByCode(planInfo.businessModelCode, businessModel);
                        $('#businessModelCode').val(planInfo.businessModelCode);
                        $('#businessModelName').val(name);
                    }

                    if(!isEmpty(planInfo.articleNumberDate)){
                        //货好日期
                        $('#articleNumberDate').val(planInfo.articleNumberDate);
                    }

                    if(!isEmpty(planInfo.warehouseCode)){
                        //仓库编码
                        let name = getWarehouseName(planInfo.warehouseCode);
                        $("#warehouseCode").val(planInfo.warehouseCode);
                        $("#warehouseName").val(name);
                    }

                    if(!isEmpty(planInfo.accountingPeriod)){
                        //账期
                        $("#accountingPeriod").val(planInfo.accountingPeriod);
                    }else {
                        $("#accountingPeriod").val(0);
                    }

                    if(!isEmpty(planInfo.carryPlanNo)){
                        //出运计划号
                        $("#carryPlanNo").val(planInfo.carryPlanNo);
                        //发票编号
                        $("#billNo").val(planInfo.carryPlanNo);
                    }

                    if(!isEmpty(planInfo.signingCompanyCode)){
                        //签约公司
                        let name = getNameByCode(planInfo.signingCompanyCode, companyInfo);
                        $('#signingCompanyCode').val(planInfo.signingCompanyCode);
                        $('#signingCompanyName').val(name);
                        //重新查询银行信息
                        getBankInfo(planInfo.signingCompanyCode);
                        if(!isEmpty(planInfo.bankCode)){
                            $('#bankCode').val(planInfo.bankCode);
                            let bankName = getNameByCode(planInfo.bankCode, bankAccountList);
                            $('#bankName').val(bankName);
                        }

                    }

                    if(!isEmpty(planInfo.inspectionProgress)){
                        //验货进度
                        let name = getNameByCode(planInfo.inspectionProgress, inspectionProgress);
                        $('#inspectionProgress').val(name);
                    }
                    if(!isEmpty(planInfo.salesmanCode)){
                        let salesmanCode = planInfo.salesmanCode;
                        //业务员
                        $("#salesmanCode").val(salesmanCode);
                        for(let i in salesmanInfo){
                            if(salesmanCode == salesmanInfo[i].code){
                                $('#salesmanName').val(salesmanInfo[i].name);
                                break;
                            }
                        }
                    }
                    if(!isEmpty(planInfo.isDeclare)){
                        //是否报关
                        $('#isDeclare').val(planInfo.isDeclare);
                    }
                    if(null != planInfo.whetherCreditGuarantee){
                        //是否走信保订单
                        $('#whetherCreditGuarantee').val(planInfo.whetherCreditGuarantee);
                    }
                    if(!isEmpty(planInfo.creditGuaranteeAmount)){
                        //信保订单金额USD
                        $('#creditGuaranteeAmount').val(planInfo.creditGuaranteeAmount);
                    }
                    form.render();
                    patentTableFlag = false;
                }

                if(!isEmpty(res.data[i].productUnitCode)){
                    $("#productUnitCode_" + tempId).val(res.data[i].productUnitCode);
                }else {
                    let unit = unitOfQuantity[0].code;
                    res.data[i].productUnitCode = unit;
                    $("#productUnitCode_" + tempId).val(unit);
                }

                //海关相关信息
                if(!isEmpty(res.data[i].customsCode)){
                    $("#customsCode_" + tempId).val(res.data[i].customsCode);
                }

                //金额小计
                let moneySubtotal = res.data[i].moneySubtotal;
                if(!checkNumber(moneySubtotal)){
                    moneySubtotal = 0;
                }
                sumMoneySubtotal = new BigNumber(sumMoneySubtotal).plus(moneySubtotal);
            }
            //sum(费用)
            let costData = table.cache["costtableid"];
            let sumAmount = 0;
            for(let i in costData){
                let amount = costData[i].amount;
                if(!checkNumber(amount)){
                    amount = 0;
                }
                sumAmount = new BigNumber(sumAmount).plus(amount);
            }
            let totalInvoiceAmount = new BigNumber(sumMoneySubtotal).plus(sumAmount).dp(2, BigNumber.ROUND_HALF_UP).toString();
            $("#totalInvoiceAmount").val(totalInvoiceAmount);
            form.render('select');
        }
    });


    form.on("select(unitselect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["storageproductstableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["productUnitCode"] = data.value;
                tableData[index]["productUnitName"] = getProductUnitCode(data.value);
            }
        });
    });

    function getProductUnitCode(code){
        for(let i in unitOfQuantity){
            if(unitOfQuantity[i].code == code){
                return unitOfQuantity[i].name;
            }
        }
        return "";
    }

    function productTableReload(){
        table.reload('storageproductstableid',{
            data:table.cache.test,
            totalRow: true,
        })
    }

    table.on('edit(storageproductstable)', function (obj) {
        let old = $(this).prev().text();//旧值
        //判断数据类型
        if ((obj.field == "productNum" ||
            obj.field == "fcUnitPrice" ||
            obj.field == "moneySubtotal" ||
            obj.field == "grossWeight" ||
            obj.field == "grossWeightSubtotal" ||
            obj.field == "netWeight" ||
            obj.field == "netWeightSubtotal" ||
            obj.field == "bulk" ||
            obj.field == "totalTray" ||
            obj.field == "trayNumber" ||
            obj.field == "boxAmount" ||
            obj.field == "everyBoxAmount" ||
            obj.field == "costUnitPrice" ||
            obj.field == "costSubtotal" ||
            obj.field == "finishedProductCost" ||
            obj.field == "accessoriesCost" ||
            obj.field == "outerPackingLong" ||
            obj.field == "outerPackingWide" ||
            obj.field == "outerPackingHeight") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
        if(obj.field == "productNum"){
            //数量(数量变更，金额小计、托数、件数、每托量、每件数量、成本小计、毛重小计、净重小计、体积小计、发票总额、对应配件的数量、成本小计重新计算)
            let productNum = obj.value;
            obj.data.productNum = productNum;//新值

            let surplusAmount=0//剩余数量
            $.ajax({
                type : 'POST',
                data: {shipmentNo:obj.data.carryPlanNo,exportCode:obj.data.saleContractNo,productCode:obj.data.productCode,specNo:obj.data.specNo},
                url:'carryDetail/getSurplusAmount',
                async:false,
                success : function (da) {
                    if(da.status==200 ){
                        surplusAmount=da.data;
                    }
                }
            });
            if (productNum>surplusAmount){
                layer.confirm('请注意输入的数量不能大于该计划对应产品剩余数量!!! </br> 剩余数量为：'+surplusAmount,{icon:3,title:'提示'});
                $(this).val(old);
                if(obj.field == "productNum"){
                    obj.update({productNum:old})
                }
                return;
            }

            //1.金额小计:金额小计=单价*数量
            let moneySubtotal = getMoneySubtotal(obj.data);
            obj.update({
                moneySubtotal :  moneySubtotal
            });
            obj.data.moneySubtotal = moneySubtotal;
            //发票总额:发票总额=sum(金额小计)+sum(费用)
            let totalInvoiceAmount = getTotalQuotation(obj.data, moneySubtotal);
            $("#totalInvoiceAmount").val(totalInvoiceAmount);

            //2.托数:托数=数量/每托量
            let totalTray = getTotalTray(obj.data);
            obj.update({
                totalTray :  totalTray
            });
            obj.data.totalTray = totalTray;

            //3.件数:件数=数量/每件数量
            let boxAmount = getBoxAmount(obj.data);
            obj.update({
                boxAmount :  boxAmount
            });
            obj.data.boxAmount = boxAmount;

            //4.每托量:每托量=数量/托数
            let trayNumber = getTrayNumber(obj.data);
            obj.update({
                trayNumber :  trayNumber
            });
            obj.data.trayNumber = trayNumber;

            //5.每件数量:每件数量=数量/件数
            let everyBoxAmount = getEveryBoxAmount(obj.data);
            obj.update({
                everyBoxAmount :  everyBoxAmount
            });
            obj.data.everyBoxAmount = everyBoxAmount;

            //6.成本小计:成本小计=数量*成本单价
            let costSubtotal = getCostSubtotal(obj.data);
            obj.update({
                costSubtotal :  costSubtotal
            });
            obj.data.costSubtotal = costSubtotal;

            //7.毛重小计:毛重小计=毛重*件数
            let grossWeightSubtotal = getGrossWeightSubtotal(obj.data);
            obj.update({
                grossWeightSubtotal :  grossWeightSubtotal
            });
            obj.data.grossWeightSubtotal = grossWeightSubtotal;

            //8.净重小计:净重小计=净重*件数
            let netWeightSubtotal = getNetWeightSubtotal(obj.data);
            obj.update({
                netWeightSubtotal :  netWeightSubtotal
            });
            obj.data.netWeightSubtotal = netWeightSubtotal;

            //9.体积小计:体积小计=体积*件数
            let bulkSubtotal = getBulkSubtotal(obj.data);
            obj.update({
                bulkSubtotal :  bulkSubtotal
            });
            obj.data.bulkSubtotal = bulkSubtotal;

            //10.对应配件的数量、成本小计重新计算
            let partsList = obj.data["partsList"];
            for(let i in partsList){
                //配建比例
                let partsFinishedProducts = partsList[i]["partsFinishedProducts"];
                //配件数量 = 配件比例*产品数量
                let partsAmount = new BigNumber(partsFinishedProducts).multipliedBy(productNum).dp(4, BigNumber.ROUND_HALF_UP).toString();
                partsList[i]["partsAmount"] = partsAmount;
                //成本单价
                let costUnitPrice = partsList[i]["costUnitPrice"];
                if(isEmpty(costUnitPrice)){
                    costUnitPrice = new BigNumber(0);
                }
                //成本小计 = 成本单价*配件数量
                let costSubtotal = new BigNumber(costUnitPrice).multipliedBy(partsAmount).dp(4, BigNumber.ROUND_HALF_UP).toString();
                partsList[i]["costSubtotal"] = costSubtotal;
            }

            //表单重载
            productTableReload();

            table.reload('productsatableid',{data:partsList})
        }
        if(obj.field == "fcUnitPrice"){
            //外币单价(外币单价变更，金额小计、发票总额重新计算)
            let fcUnitPrice = obj.value;
            obj.data.fcUnitPrice = fcUnitPrice;

            //1.金额小计:金额小计=单价*数量
            let moneySubtotal = getMoneySubtotal(obj.data);
            obj.update({
                moneySubtotal :  moneySubtotal
            });
            obj.data.moneySubtotal = moneySubtotal;
            //发票总额:发票总额=sum(金额小计)+sum(费用)
            let totalInvoiceAmount = getTotalQuotation(obj.data, moneySubtotal);
            $("#totalInvoiceAmount").val(totalInvoiceAmount);

            //表单重载
            productTableReload();
        }
        if(obj.field == "moneySubtotal"){
            //金额小计(金额小计变更，发票总额重新计算)
            let moneySubtotal = obj.value;
            obj.data.moneySubtotal = moneySubtotal;
            //发票总额:发票总额=sum(金额小计)+sum(费用)
            let totalInvoiceAmount = getTotalQuotation(obj.data, moneySubtotal);
            $("#totalInvoiceAmount").val(totalInvoiceAmount);

            //表单重载
            productTableReload();
        }
        if(obj.field == "totalTray"){
            //托数(托数变更，每托量重新计算)
            let totalTray = obj.value;
            obj.data.totalTray = totalTray;

            //1.每托量:每托量=数量/托数
            let trayNumber = getTrayNumber(obj.data);
            obj.update({
                trayNumber :  trayNumber
            });
            obj.data.trayNumber = trayNumber;
        }
        if(obj.field == "trayNumber"){
            //每托量(每托量变更，托数重新计算)
            let trayNumber = obj.value;
            obj.data.trayNumber = trayNumber;

            //1.托数:托数=数量/每托量
            let totalTray = getTotalTray(obj.data);
            obj.update({
                totalTray :  totalTray
            });
            obj.data.totalTray = totalTray;
        }
        if(obj.field == "boxAmount"){
            //件数(件数变更，每件数量、毛重小计、净重小计、体积小计重新计算)
            let boxAmount = obj.value;
            obj.data.boxAmount = boxAmount;

            //1.每件数量:每件数量=数量/件数
            let everyBoxAmount = getEveryBoxAmount(obj.data);
            obj.update({
                everyBoxAmount :  everyBoxAmount
            });
            obj.data.everyBoxAmount = everyBoxAmount;

            //2.毛重小计:毛重小计=毛重*件数
            let grossWeightSubtotal = getGrossWeightSubtotal(obj.data);
            obj.update({
                grossWeightSubtotal :  grossWeightSubtotal
            });
            obj.data.grossWeightSubtotal = grossWeightSubtotal;

            //3.净重小计:净重小计=净重*件数
            let netWeightSubtotal = getNetWeightSubtotal(obj.data);
            obj.update({
                netWeightSubtotal :  netWeightSubtotal
            });
            obj.data.netWeightSubtotal = netWeightSubtotal;

            //4.体积小计:体积小计=体积*件数
            let bulkSubtotal = getBulkSubtotal(obj.data);
            obj.update({
                bulkSubtotal :  bulkSubtotal
            });
            obj.data.bulkSubtotal = bulkSubtotal;
        }
        if(obj.field == "everyBoxAmount"){
            //每件数量(每件数量变更，件数重新计算)
            let everyBoxAmount = obj.value;
            obj.data.everyBoxAmount = everyBoxAmount;

            //1.件数:件数=数量/每件数量
            let boxAmount = getBoxAmount(obj.data);
            obj.update({
                boxAmount :  boxAmount
            });
            obj.data.boxAmount = boxAmount;
        }
        if(obj.field == "finishedProductCost"){
            //成品成本(成品成本变更，成本单价、成本小计、配件成本重新计算)
            let finishedProductCost = obj.value;
            obj.data.finishedProductCost = finishedProductCost;

            //1.成本单价:成本单价=成品成本+配件成本
            let costUnitPrice = getCostUnitPrice(obj.data);
            obj.update({
                costUnitPrice :  costUnitPrice
            });
            obj.data.costUnitPrice = costUnitPrice;

            //2.成本小计:成本小计=数量*成本单价
            let costSubtotal = getCostSubtotal(obj.data);
            obj.update({
                costSubtotal :  costSubtotal
            });
            obj.data.costSubtotal = costSubtotal;

            //3.配件成本:配件成本=sum(成本单价)
            let accessoriesCost = getAccessoriesCost(obj.data);
            obj.update({
                accessoriesCost :  accessoriesCost
            });
            obj.data.accessoriesCost = accessoriesCost;
        }
        if(obj.field == "accessoriesCost"){
            //配件成本(配件成本变更，成本单价、成本小计重新计算)
            let accessoriesCost = obj.value;
            obj.data.accessoriesCost = accessoriesCost;

            //1.成本单价:成本单价=成品成本+配件成本
            let costUnitPrice = getCostUnitPrice(obj.data);
            obj.update({
                costUnitPrice :  costUnitPrice
            });
            obj.data.costUnitPrice = costUnitPrice;

            //2.成本小计:成本小计=数量*成本单价
            let costSubtotal = getCostSubtotal(obj.data);
            obj.update({
                costSubtotal :  costSubtotal
            });
            obj.data.costSubtotal = costSubtotal;
        }
        if(obj.field == "costUnitPrice"){
            //成本单价(成本单价变更，成本小计、配件成本重新计算)
            let costUnitPrice = obj.value;
            obj.data.costUnitPrice = costUnitPrice;

            //1.成本小计:成本小计=数量*成本单价
            let costSubtotal = getCostSubtotal(obj.data);
            obj.update({
                costSubtotal :  costSubtotal
            });
            obj.data.costSubtotal = costSubtotal;

            //2.配件成本:配件成本=sum(成本单价)
            let accessoriesCost = getAccessoriesCost(obj.data);
            obj.update({
                accessoriesCost :  accessoriesCost
            });
            obj.data.accessoriesCost = accessoriesCost;
        }

    });

    //配件成本=sum(成本单价)
    function getAccessoriesCost(data) {
        let sum = 0;
        let partsList = data.partsList;
        if(isEmpty(partsList)){
            return sum;
        }
        for(let i in partsList){
            let costUnitPrice = partsList[i]["costUnitPrice"];
            if(!isEmpty(costUnitPrice)){
                sum = sum.plus(costUnitPrice);
            }
        }
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //成本单价=成品成本+配件成本
    function getCostUnitPrice(data) {
        //成品成本
        let finishedProductCost = data.finishedProductCost;
        if(!checkNumber(finishedProductCost)){
            finishedProductCost = 0;
        }
        //配件成本
        let accessoriesCost = data.accessoriesCost;
        if(!checkNumber(accessoriesCost)){
            accessoriesCost = 0;
        }
        //四舍五入保留4位小数
        let sum = new BigNumber(finishedProductCost).plus(accessoriesCost);
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //发票总额=sum(金额小计)+sum(费用)
    function getTotalQuotation(data, currentData) {
        let productData = table.cache["storageproductstableid"];
        //sum(金额小计)
        let sumMoneySubtotal = 0;
        for(let i in productData){
            if(productData[i].tempId == data.tempId){
                continue;
            }
            //金额小计
            let moneySubtotal = productData[i].moneySubtotal;
            if(!checkNumber(moneySubtotal)){
                moneySubtotal = 0;
            }
            sumMoneySubtotal = new BigNumber(sumMoneySubtotal).plus(moneySubtotal);
        }
        //sum(费用)
        let costData = table.cache["costtableid"];
        let sumAmount = 0;
        for(let i in costData){
            let amount = costData[i].amount;
            if(!checkNumber(amount)){
                amount = 0;
            }
            sumAmount = new BigNumber(sumAmount).plus(amount);
        }
        let sum = new BigNumber(sumMoneySubtotal).plus(sumAmount).plus(currentData).dp(2, BigNumber.ROUND_HALF_UP).toString();
        return sum;
    }

    //体积小计=体积*件数
    function getBulkSubtotal(data) {
        //体积
        let bulk = data.bulk;
        if(!checkNumber(bulk)){
            return 0;
        }
        //件数
        let boxAmount = data.boxAmount;
        if(!checkNumber(boxAmount)){
            return 0;
        }
        //四舍五入保留4位小数
        let sum = new BigNumber(bulk).multipliedBy(boxAmount);
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //净重小计=净重*件数
    function getNetWeightSubtotal(data) {
        //净重
        let netWeight = data.netWeight;
        if(!checkNumber(netWeight)){
            return 0;
        }
        //件数
        let boxAmount = data.boxAmount;
        if(!checkNumber(boxAmount)){
            return 0;
        }
        //四舍五入保留4位小数
        let sum = new BigNumber(netWeight).multipliedBy(boxAmount);
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //毛重小计=毛重*件数
    function getGrossWeightSubtotal(data) {
        //毛重
        let grossWeight = data.grossWeight;
        if(!checkNumber(grossWeight)){
            return 0;
        }
        //件数
        let boxAmount = data.boxAmount;
        if(!checkNumber(boxAmount)){
            return 0;
        }
        //四舍五入保留4位小数
        let sum = new BigNumber(grossWeight).multipliedBy(boxAmount);
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //成本小计=数量*成本单价
    function getCostSubtotal(data) {
        //数量
        let productNum = data.productNum;
        if(!checkNumber(productNum)){
            return 0;
        }
        //成本单价
        let costUnitPrice = data.costUnitPrice;
        if(!checkNumber(costUnitPrice)){
            return 0;
        }
        //四舍五入保留4位小数
        let sum = new BigNumber(productNum).multipliedBy(costUnitPrice);
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //每件数量:每件数量=数量/件数
    function getEveryBoxAmount(data) {
        //数量
        let productNum = data.productNum;
        if(!checkNumber(productNum)){
            return 0;
        }
        //件数
        let boxAmount = data.boxAmount;
        if(!checkNumber(boxAmount)){
            return 0;
        }
        //四舍五入保留4位小数
        let sum = new BigNumber(productNum).dividedBy(boxAmount);
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //每托量:每托量=数量/托数
    function getTrayNumber(data) {
        //数量
        let productNum = data.productNum;
        if(!checkNumber(productNum)){
            return 0;
        }
        //托数
        let totalTray = data.totalTray;
        if(!checkNumber(totalTray)){
            return 0;
        }
        //四舍五入保留4位小数
        let sum = new BigNumber(productNum).dividedBy(totalTray);
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //件数:件数=数量/每件数量
    function getBoxAmount(data) {
        //数量
        let productNum = data.productNum;
        if(!checkNumber(productNum)){
            return 0;
        }
        //每件数量
        let everyBoxAmount = data.everyBoxAmount;
        if(!checkNumber(everyBoxAmount)){
            return 0;
        }
        //四舍五入保留4位小数
        let sum = new BigNumber(productNum).dividedBy(everyBoxAmount);
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //托数:托数=数量/每托量
    function getTotalTray(data) {
        //数量
        let productNum = data.productNum;
        if(!checkNumber(productNum)){
            return 0;
        }
        //每托量
        let trayNumber = data.trayNumber;
        if(!checkNumber(trayNumber)){
            return 0;
        }
        //四舍五入保留4位小数
        let sum = new BigNumber(productNum).dividedBy(trayNumber);
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //金额小计:金额小计=单价*数量
    function getMoneySubtotal(data){
        //单价
        let fcUnitPrice = data.fcUnitPrice;
        if(!checkNumber(fcUnitPrice)){
            return 0;
        }
        //数量
        let productNum = data.productNum;
        if(!checkNumber(productNum)){
            return 0;
        }
        //四舍五入保留4位小数
        let sum = new BigNumber(fcUnitPrice).multipliedBy(productNum);
        return sum.dp(4, BigNumber.ROUND_HALF_UP).toString();
    }

    //产品明细单个删除
    table.on('tool(storageproductstable)', function (obj) {
        let data = obj.data;
        let oldData =  table.cache["storageproductstableid"];
        if (obj.event === 'del') {
            layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
                for(let i in oldData){
                    if(oldData[i].tempId == data.tempId){
                        oldData.splice(i, 1);
                        table.reload('storageproductstableid',{data : oldData});
                        let defData = [];
                        table.reload("productsatableid", {data: defData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });
        }
    });

    function tobottomfn(id){
        let d=$("[lay-id='"+id+"'] .layui-table-main").get(0)
        let h=d.scrollHeight
        d.scrollTo(0,h)
    }

    table.on('toolbar(storageproductstable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'importshipmentplan':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['80%', '95%'],
                    content: 'views/jsp/ExportBusiness/tpl/importshipmentplan.jsp'
                });
                break;
            case 'planassociatedtransfers':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['80%', '95%'],
                    content: 'views/jsp/ExportBusiness/tpl/planassociatedtransfers.jsp'
                });
                break;
            case 'new':
                let oldData = table.cache["storageproductstableid"];
                let tempId = GenNonDuplicateID(3) + (oldData.length + 1);
                let newData = {
                    "tempId": tempId,
                    "productNum": 0,
                    "fcUnitPrice" : 0,
                    "moneySubtotal" : 0,
                    "grossWeight" : 0,
                    "grossWeightSubtotal" : 0,
                    "netWeight" : 0,
                    "netWeightSubtotal" : 0,
                    "bulk" : 0,
                    "totalTray" : 0,
                    "trayNumber" : 0,
                    "boxAmount" : 0,
                    "everyBoxAmount" : 0,
                    "costUnitPrice" : 0,
                    "costSubtotal" : 0,
                    "finishedProductCost": 0,
                    "accessoriesCost" : 0,
                    "outerPackingLong" : 0,
                    "outerPackingWide" : 0,
                    "outerPackingHeight" : 0
                };
                oldData.push(newData);
                table.reload('storageproductstableid', {data: oldData, limit:oldData.length});
                tobottomfn("storageproductstableid");
                break;
            case 'del':
                let data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.tempId);
                });
                if (delList != '') {
                    layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
                        let cbList = table.cache["storageproductstableid"];
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("storageproductstableid", {
                            data: cbList,
                        });
                        let defData = [];
                        table.reload("productsatableid", {data: defData});
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });

    //监听行单击事件 配件表
    table.on('row(storageproductstable)', function (obj) {
        $("#hidden").show();
        partsParentTempId = obj.data.tempId;
        let initParts = [];
        if(!isEmpty(obj.data.partsList)){
            initParts = obj.data.partsList;
        }
        table.render({
            elem: '#productsaselect'
            , data: initParts
            , toolbar: '#productsatoolbar'
            , cols: [[
                {checkbox: true, fixed: true}
                , {field: 'partsCode', title: '产品编码', edit: 'text',width: 220}
                , {field: 'specNo', title: '规格编码', edit: 'text'}
                , {field: 'proportionFinishedProducts', title: '成品比例', edit: 'text'}
                , {field: 'partsFinishedProducts', title: '配件比例', edit: 'text'}
                , {field: 'partsAmount', title: '配件数量'}
                , {field: 'costUnitPrice', width: 120, title: '成本单价'}
                , {field: 'costSubtotal', width: 120, title: '成本小计'}
                , {field: 'supplierName', width: 120, title: '供应商'}
                , {field: 'purchaseNo', width: 120, title: '采购单号', edit: 'text'}
                , {field: 'productCname', title: '中文名称', edit: 'text'}
                , {field: 'productEname', title: '英文名称', edit: 'text'}
                , {field: 'grossWeight', title: '毛重', edit: 'text'}
                , {field: 'netWeight', title: '净重', edit: 'text'}
                , {field: 'bulk', title: '体积', edit: 'text'}
                , {fixed: 'right', width: 150, align: 'center', toolbar: '#productsaup', title: '操作'}
            ]]
            , id: 'productsatableid'
            ,page: false
            ,limit: Number.MAX_VALUE
            ,height: 300
            ,done:function (res, curr, count) {
                if(exportConcatLabel){
                    //外销标签:控制子表"成本单价"、"成本小计"、"成品成本"、"配件成本"、"供应商" 配件表 "成本单价"、"成本小计"、"供应商"
                    //成本单价
                    $("[data-field='costUnitPrice']").css("display", "none");
                    //成本小计
                    $("[data-field='costSubtotal']").css("display", "none");
                    //供应商
                    $("[data-field='supplierName']").css("display", "none");

                }
            }
        });
    });
    table.on('edit(productsatable)', function (obj) {
        let old = $(this).prev().text();//旧值
        //判断数据类型
        if ((obj.field == "proportionFinishedProducts" ||
            obj.field == "partsFinishedProducts" ||
            obj.field == "partsAmount" ||
            obj.field == "costUnitPrice" ||
            obj.field == "costSubtotal" ||
            obj.field == "grossWeight" ||
            obj.field == "netWeight" ||
            obj.field == "bulk") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
        let parentTable = table.cache["storageproductstableid"];
        for(let k in parentTable){
            if(parentTable[k].tempId == partsParentTempId){
                let partsList = parentTable[k].partsList;
                let productNum = parentTable[k].productNum;
                for(let j in partsList){
                    if(partsList[j].tempId == obj.data.tempId){
                        if(obj.field == "partsFinishedProducts"){
                            //配件比例
                            partsList[j]["partsFinishedProducts"] = obj.value;
                            let sum = new BigNumber(productNum).multipliedBy(obj.value).dp(4, BigNumber.ROUND_HALF_UP).toString();
                            partsList[j]["partsAmount"] = sum;
                            //成本单价
                            let costUnitPrice = partsList[j]["costUnitPrice"];
                            if(isEmpty(costUnitPrice)){
                                costUnitPrice = new BigNumber(0);
                            }
                            //成本小计 = 成本单价*配件数量
                            let costSubtotal = new BigNumber(costUnitPrice).multipliedBy(sum).dp(4, BigNumber.ROUND_HALF_UP).toString();
                            partsList[j]["costSubtotal"] = costSubtotal;
                            break;
                        }
                        if(obj.field == "partsCode"){
                            //配件编码
                            partsList[j]["partsCode"] = obj.value;
                            break;
                        }
                        if(obj.field == "specNo"){
                            //规格编码
                            partsList[j]["specNo"] = obj.value;
                            break;
                        }
                        if(obj.field == "proportionFinishedProducts"){
                            //成品比例
                            partsList[j]["proportionFinishedProducts"] = obj.value;
                            break;
                        }
                        if(obj.field == "partsAmount"){
                            //数量
                            partsList[j]["partsAmount"] = obj.value;
                            break;
                        }
                        if(obj.field == "productCname"){
                            //中文名称
                            partsList[j]["productCname"] = obj.value;
                            break;
                        }
                        if(obj.field == "productEname"){
                            //英文名称
                            partsList[j]["productEname"] = obj.value;
                            break;
                        }
                        if(obj.field == "grossWeight"){
                            //毛重
                            partsList[j]["grossWeight"] = obj.value;
                            break;
                        }
                        if(obj.field == "netWeight"){
                            //净重
                            partsList[j]["netWeight"] = obj.value;
                            break;
                        }
                        if(obj.field == "bulk"){
                            //体积
                            partsList[j]["bulk"] = obj.value;
                            break;
                        }
                        if(obj.field == "costUnitPrice"){
                            //成本单价
                            partsList[j]["costUnitPrice"] = obj.value;
                            break;
                        }
                        if(obj.field == "costSubtotal"){
                            //成本小计
                            partsList[j]["costSubtotal"] = obj.value;
                            break;
                        }
                        if(obj.field == "supplierName"){
                            //供应商
                            partsList[j]["supplierName"] = obj.value;
                            break;
                        }
                    }
                }
                parentTable[k]["partsList"] = partsList;
                table.reload("storageproductstableid", {data: parentTable});
                table.reload("productsatableid", {data: partsList});
                break;
            }
        }
    });


    //配件新增、删除
    table.on('toolbar(productsatable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'new':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['80%', '95%'],
                    content: 'views/jsp/ExportBusiness/tpl/productlibraryimport.jsp?tableid=productsatableid&modelId=offer&partsParentTempId='+partsParentTempId
                });
                break;
            case 'delet':
                let data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.tempId);
                });
                if (delList != '') {
                    layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
                        let cbList = table.cache["productsatableid"];
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        //删除对应配件信息
                        deleteProductParts(cbList);
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });

    //删除对应配件信息
    function deleteProductParts(oldData){
        let parentTable = table.cache["storageproductstableid"];
        for(let k in parentTable){
            if(parentTable[k].tempId == partsParentTempId){
                parentTable[k]["partsList"] = oldData;
                break;
            }
        }
        table.reload("storageproductstableid", {
            data: parentTable
        });
        table.reload("productsatableid", {
            data: oldData
        });
    }

    //配件表单个删除
    table.on('tool(productsatable)', function (obj) {
        let data = obj.data;
        let oldData =  table.cache["productsatableid"];
        if (obj.event === 'productsade') {
            layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
                for(let i in oldData){
                    if(oldData[i].tempId == data.tempId){
                        oldData.splice(i, 1);
                        break;
                    }
                }
                //删除对应配件信息
                deleteProductParts(oldData);
                layer.msg('删除成功');
                layer.close(index);
            });
        }
    });

    //---费用
    let initCost = [];
    table.render({
        elem: '#cost'
        , data: initCost
        , toolbar: '#costtoolbar'
        , cols: [[
            {checkbox: true, fixed: true}
            , {field: 'typeCode', title: '费用类型', templet: '#costtypeselect'}
            , {field: 'amount', title: '金额', event: 'amount', edit: 'text'}
            , {field: 'contractNo', title: '外销合同号', event: 'contractNo', edit: 'text'}
            , {field: 'memo', title: '备注说明', edit: 'text'}
        ]]
        , id: 'costtableid'
        , height: 380
        ,page: false
        ,limit: Number.MAX_VALUE
        , done: function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
            for(let i in costType){
                $(".typeCode").append("<option value=\"" + costType[i].code + "\">" + costType[i].name + "</option>");
            }
            //sum(费用)
            let sumAmount = 0;
            for (var i = 0; i < res.data.length; i++) {
                let tempId = res.data[i].tempId;
                $("#typeCode_" + tempId).val(res.data[i].typeCode);
                res.data[i]["typeName"] = getTypeNameByCode(res.data[i].typeCode);
                let amount = res.data[i].amount;
                if(!checkNumber(amount)){
                    amount = 0;
                }
                sumAmount = new BigNumber(sumAmount).plus(amount);
            }
            let productData = table.cache["storageproductstableid"];
            //sum(金额小计)
            let sumMoneySubtotal = 0;
            for(let i in productData){
                //金额小计
                let moneySubtotal = productData[i].moneySubtotal;
                if(!checkNumber(moneySubtotal)){
                    moneySubtotal = 0;
                }
                sumMoneySubtotal = new BigNumber(sumMoneySubtotal).plus(moneySubtotal);
            }
            //发票总额=sum(金额小计)+sum(费用)
            let totalInvoiceAmount = new BigNumber(sumMoneySubtotal).plus(sumAmount).dp(2, BigNumber.ROUND_HALF_UP).toString();
            $("#totalInvoiceAmount").val(totalInvoiceAmount);

            form.render('select');
        }
    });

    //监听费用编辑
    table.on('edit(costtable)', function (obj) {
        let old = $(this).prev().text();//旧值
        //判断数据类型
        if ((obj.field == "amount") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
        if(obj.field == "amount"){
            //重新计算合同总额
            let productData = table.cache["storageproductstableid"];
            //sum(金额小计)
            let sumMoneySubtotal = 0;
            for(let i in productData){
                //金额小计
                let moneySubtotal = productData[i].moneySubtotal;
                if(!checkNumber(moneySubtotal)){
                    moneySubtotal = 0;
                }
                sumMoneySubtotal = new BigNumber(sumMoneySubtotal).plus(moneySubtotal);
            }

            //sum(费用)
            let costData = table.cache["costtableid"];
            let sumAmount = 0;
            for(let i in costData){
                if(costData[i].tempId == obj.data.tempId){
                    continue;
                }
                let amount = costData[i].amount;
                if(!checkNumber(amount)){
                    amount = 0;
                }
                sumAmount = new BigNumber(sumAmount).plus(amount);
            }
            let totalInvoiceAmount = new BigNumber(sumMoneySubtotal).plus(sumAmount).plus(obj.value).dp(4, BigNumber.ROUND_HALF_UP).toString();
            $("#totalInvoiceAmount").val(totalInvoiceAmount);

            form.render();
        }
    });

    form.on("select(costtypeselect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["costtableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["typeCode"] = data.value;
                tableData[index]["typeName"] = getTypeNameByCode(data.value);
            }
        });
    });

    function getTypeNameByCode(code){
        for(let i in costType){
            if(costType[i].code == code){
                return costType[i].name;
            }
        }
        return "";
    }

    table.on('toolbar(costtable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'new':
                let oldData = table.cache["costtableid"];
                let tempId = GenNonDuplicateID(3) + (oldData.length + 1);
                let newData = {
                    "tempId" : tempId,
                    "typeCode" : "",
                    "amount" : 0,
                    "contractNo" : "",
                    "memo" : ""
                };
                oldData.push(newData);
                table.reload('costtableid', {data: oldData, limit: oldData.length});
                tobottomfn("costtableid");
                break;
            case 'del':
                let data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.tempId);
                });
                if (delList != '') {
                    layer.confirm('确定删除所选项吗？',confirmInfo(3,6), function (index) {
                        let cbList = table.cache["costtableid"];
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("costtableid", {
                            data: cbList,
                        });
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });


    //---附件
    table.render({
        elem: '#attachment'
        , data: annexList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName', event:'fileName', title: '文件名', fixed: true}
            , {field: 'uploadTime', title: '上传日期', fixed: true, sort:true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
        , done: function (res, index, upload) {
            let data = res.data;
            for(let i in data){
                let flag = true;
                for(let j in annexList){
                    if(data[i].id == annexList[j].id){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    annexList.push(data[i]);
                }
            }
        }
    });

    upload.render({
        elem: '#uploadfile'
        , url: 'transfer/uploadFile'
        , field: "uploadify"
        , accept: 'file'
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , parseData: function(res){
            return {
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
        , done: function (res, index, upload) {
            let data = res.data;
            for(var i in data){
                if (data[i].status) { //上传成功
                    annexList.push(data[i]);
                    var tr = $("#uploadlist").find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                    }
                });
                break;
        }
        ;
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            let xmlHttpRequest = new XMLHttpRequest();
            let url = "wjinfo/downloadfile2?filename=" + data.filePath;
            xmlHttpRequest.open('GET', url, true);
            //设置请求头
            xmlHttpRequest.setRequestHeader("Content-type", "application/json")
            xmlHttpRequest.responseType = "blob";
            xmlHttpRequest.send(null);

            xmlHttpRequest.onload = function() {
                let content = xmlHttpRequest.response;
                // 组装a标签
                let elink = document.createElement("a");

                //设置文件下载路径
                elink.download = decodeURIComponent(data.fileName);
                elink.style.display = "none";
                let blob = new Blob([content], { type: 'application/force-download' });

                //解决下载不存在文件的问题，根据blob大小判断
                if(blob.size==0){
                    layer.msg('服务器没找到此文件，请联系管理员!');
                }else{
                    elink.href = window.URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }

            }
        } else if (obj.event === 'del') {
            layer.confirm('确认删除?',
                confirmInfo(3,5), function (index) {
                    obj.del();
                    let id = data.id;
                    for (var i = 0; i < annexList.length; i++) {
                        if (annexList[i].id == id) {
                            if(0 == annexList[i]["news"]){
                                //记录被删除的老的附件
                                deleteAnnexIds.push(id);
                            }
                            annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                            i--; // 如果不减，将漏掉一个元素
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                    table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
                });
        } else if (obj.event === 'fileName') {
            onLineFile(data.filePath);
        }
    });

    //---操作日志
    let initOperation = [];
    table.render({
        elem: '#otherwarehouselog'
        , data: initOperation
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });


    function isNumber(val) {
        let regPos = /^\d+(\.\d+)?$/; //非负浮点数
        let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if (regPos.test(val) || regNeg.test(val)) {
            return true;
        } else {
            return false;
        }
    }

    //时间处理 获取当前时间type:1 yyyy-MM-dd type:2 yyyyMMdd+毫秒
    function getNowFormatDate(type) {
        let date = new Date();
        let separator = "-";
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if (1 == type) {
            let currentDate = year + separator + month + separator + strDate;
            return currentDate;
        } else if (2 == type) {
            let second = date.getMilliseconds().toString();
            if (second.length < 3) {
                if (second.length == 1) {
                    second = "0" + "0" + second;
                } else {
                    second = "0" + second;
                }
            }
            let currentDate = year.toString() + month.toString() + strDate.toString() + second;
            return currentDate;
        }

    }

    let currentDate = getNowFormatDate(1);
    //出运日期
    laydate.render({
        elem: '#time',
        value: currentDate,
        isInitValue: true
    });

    //制单时间
    laydate.render({
        elem: '#createDate',
        value: currentDate,
        min: currentDate,
        max: currentDate,
        btns: ['confirm']
    });


    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }

    function checkNumber(val) {
        if(isEmpty(val)){
            return false;
        }
        if(!isNumber(val)){
            return false;
        }
        return true;
    }

});

//生成临时id
function GenNonDuplicateID(randomLength){
    return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}